package org.crystalrange.documents.web;

import java.util.List;

import org.crystalrange.documents.model.Document;
import org.crystalrange.documents.service.DocumentService;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.util.GenericForwardComposer;
import org.zkoss.zkplus.databind.AnnotateDataBinder;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Window;

import com.googlecode.genericdao.search.Search;

public class DocumentSelectController extends GenericForwardComposer {

	protected DocumentService documentService;
	protected Document selectedDocument;
	protected List<Document> documents;
	protected Search searchDocument;
	protected AnnotateDataBinder binder;

	public DocumentService getDocumentService() {
		return documentService;
	}

	public void setDocumentService(DocumentService documentService) {
		this.documentService = documentService;
	}

	public Document getSelectedDocument() {
		return selectedDocument;
	}

	public void setSelectedDocument(Document selectedDocument) {
		this.selectedDocument = selectedDocument;
	}

	public List<Document> getDocuments() {
		return documents;
	}

	public void setDocuments(List<Document> documents) {
		this.documents = documents;
	}

	@Override
	public void doAfterCompose(Component component) throws Exception {
		super.doAfterCompose(component);
		this.searchDocument = new Search(Document.class);
		this.searchDocument.setMaxResults(100);
		this.searchDocument.addFetch("createdBy");
		this.documents = this.documentService.search(this.searchDocument);
		component.setAttribute("controller", this);
	}

	public void onClick$buttonOk(Event event) throws Exception {
		if (this.selectedDocument != null) {
			this.execution.setAttribute("selectedDocument",
					this.selectedDocument);
			this.execution.setAttribute("result", "ok");
			this.self.detach();
		} else {
			Messagebox.show("Please select a Document.");
		}
	}

	public void onClick$buttonCancel(Event event) throws Exception {
		this.execution.setAttribute("selectedDocument", null);
		this.execution.setAttribute("result", "cancel");
		this.self.detach();
	}

	public void onClick$buttonSearch(Event event) throws Exception {
		this.execution.setAttribute("searchDocument", this.searchDocument);

		Window window = (Window) this.execution.createComponents(
				"~./zul/html/documentSearch.zul", null, null);
		window.setParent(self);
		window.doModal();

		if (this.execution.getAttribute("result") == "ok") {
			this.searchDocument = (Search) this.execution
					.getAttribute("searchDocument");
		}

		this.documents = this.documentService.search(this.searchDocument);
		this.binder.loadAll();
	}

}
